﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using ViewStateToDb.Data;
using ViewStateToDb.Data.SqlServer;

namespace ViewStateToDb
{
	public class DbPageStatePersister : PageStatePersister
	{
		private Guid _viewStateId;
		private IDataProvider _dataProvider;
		private readonly ViewStateToDbConfiguration _configuration;

		/// <summary>
		/// ViewState identifier.
		/// </summary>
		public Guid ViewStateId
		{
			get
			{
				// Get the viewstate id from form parameter.
				// If unset, create new guid.
				if (_viewStateId == Guid.Empty)
					if (Page.Request.Form[_configuration.ViewStateIdHiddenField] == null)
						_viewStateId = Guid.NewGuid();
					else
						_viewStateId = new Guid(Page.Request.Form[_configuration.ViewStateIdHiddenField]);

				return _viewStateId;
			}
		}

		public DbPageStatePersister(Page page, ViewStateToDbConfiguration configuration)
			: base(page)
		{
			_configuration = configuration;
			_dataProvider = new SqlServerDataProvider(_configuration);

			page.ClientScript.RegisterHiddenField(_configuration.ViewStateIdHiddenField, ViewStateId.ToString());
		}

		/// <summary>
		/// Loads the viewstate from database.
		/// </summary>
		public override void Load()
		{
			var serializedStateData = _dataProvider.GetViewState(ViewStateId);

			if (serializedStateData == null)
				return;

			var stateData = (StateItem) StateFormatter.Deserialize(serializedStateData);

			if (stateData.ControlState != null)
				ControlState = stateData.ControlState;

			if (stateData.ViewState != null)
				ViewState = stateData.ViewState;
		}
		/// <summary>
		/// Saves the viewstate to database.
		/// </summary>
		public override void Save()
		{
			var stateData = new StateItem();
			stateData.ControlState = ControlState;
			stateData.ViewState = ViewState;

			string serializedStateData = StateFormatter.Serialize(stateData);

			_dataProvider.SaveViewState(ViewStateId, serializedStateData);
		}
	}
}
